package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.Bean;
import dao.ClientDAO;
import dao.GoodsDAO;

public class GoodsServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();

		Bean bean = new Bean();
		GoodsDAO dao = new GoodsDAO();

		int kind = Integer.parseInt(request.getParameter("kind"));

		if (kind == 1) {
			String name = request.getParameter("name");
			int money = Integer.parseInt(request.getParameter("money"));
			int num = Integer.parseInt(request.getParameter("num"));
			String description = request.getParameter("description");
			bean.setName(name);
			bean.setMoney(money);
			bean.setNum(num);
			bean.setDescription(description);
			int i = dao.add(bean);
			if (i > 0) {
				out.print("<script>alert('操作成功！');location.href='admin/goods_add.jsp';</script>");
			} else {
				out.print("<script>alert('操作失败！');history.go(-1);</script>");
			}
		} else if (kind == 2) {
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");
			int money = Integer.parseInt(request.getParameter("money"));
			int num = Integer.parseInt(request.getParameter("num"));
			String description = request.getParameter("description");
			bean.setName(name);
			bean.setMoney(money);
			bean.setNum(num);
			bean.setDescription(description);
			int i = dao.update(bean, id);
			if (i > 0) {
				out.print("<script>alert('操作成功！');location.href='admin/goods_edit.jsp?id="
						+ id + "';</script>");
			} else {
				out.print("<script>alert('操作失败！');history.go(-1);</script>");
			}
		} else if (kind == 3) {
			int id = Integer.parseInt(request.getParameter("id"));
			int i = dao.delete(id);
			if (i > 0) {
				out.print("<script>alert('操作成功！');location.href='admin/goods_list.jsp';</script>");
			} else {
				out.print("<script>alert('操作失败！');history.go(-1);</script>");
			}
		}

	}

}
